package com.ard.camera.demos;

import com.ard.camera.demos.config.HostMonitorConfig;
import com.ard.camera.demos.entry.DvrHostEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DvrHostFileReader {

    @Autowired
    private HostMonitorConfig config;

    /**
     * 读取所有硬盘录像机的主机配置
     */
    public Map<String, List<DvrHostEntry>> readAllDvrHosts() {
        Map<String, List<DvrHostEntry>> allDvrHosts = new HashMap<>();
        String dirPath = config.getHostDir();
        String suffix = config.getFileSuffix();

        try {
            File dir = new File(dirPath);
            if (!dir.exists()) {
                // 如果目录不存在，尝试从classpath读取
                ClassPathResource resource = new ClassPathResource(dirPath);
                if (resource.exists()) {
                    // 注意：ClassPathResource对于目录的处理有限
                    // 这里我们简单创建示例目录
                    dir.mkdirs();
                    createSampleDvrFiles(dir, suffix);
                } else {
                    log.warn("主机目录不存在: {}", dirPath);
                    // 创建示例目录和文件
                    dir.mkdirs();
                    createSampleDvrFiles(dir, suffix);
                }
            }

            // 读取目录下所有指定后缀的文件
            File[] files = dir.listFiles((d, name) -> name.endsWith(suffix));
            if (files == null || files.length == 0) {
                log.warn("在目录 {} 中未找到 {} 文件", dirPath, suffix);
                return allDvrHosts;
            }

            for (File file : files) {
                // 文件名（去掉后缀）作为硬盘录像机IP
                String dvrIp = file.getName().replace(suffix, "");
                List<DvrHostEntry> hostEntries = readDvrHostFile(file, dvrIp);
                allDvrHosts.put(dvrIp, hostEntries);

                log.info("读取硬盘录像机 {} 的主机配置，包含 {} 个主机", dvrIp, hostEntries.size());
            }

        } catch (Exception e) {
            log.error("读取硬盘录像机主机配置失败: {}", dirPath, e);
        }

        log.info("共读取 {} 个硬盘录像机的配置", allDvrHosts.size());
        return allDvrHosts;
    }

    /**
     * 读取单个硬盘录像机的主机文件
     */
    private List<DvrHostEntry> readDvrHostFile(File file, String dvrIp) throws IOException {
        List<DvrHostEntry> entries = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { // 关键修改
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                // 跳过空行和注释
                if (!line.isEmpty() && !line.startsWith("#")) {
                    try {
                        DvrHostEntry entry = DvrHostEntry.fromString(line, dvrIp);
                        entries.add(entry);
                    } catch (Exception e) {
                        log.warn("无法解析硬盘录像机文件行: {}，在文件: {}，错误: {}",
                                line, file.getName(), e.getMessage());
                    }
                }
            }
        }
        return entries;
    }

    /**
     * 创建示例硬盘录像机文件
     */
    private void createSampleDvrFiles(File dir, String suffix) {
        // 示例：创建三个硬盘录像机的监控文件
        String[] dvrIps = {"192.168.1.100", "192.168.1.101", "192.168.1.102"};

        for (String dvrIp : dvrIps) {
            File file = new File(dir, dvrIp + suffix);
            try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
                writer.println("# 硬盘录像机 " + dvrIp + " 的主机列表");
                writer.println("# 格式：主机地址:主机名称");
                writer.println("# 每行一个主机，#开头为注释");
                writer.println();
                writer.println("# 网络设备");
                writer.println("192.168.2.1:核心交换机");
                writer.println("192.168.2.2:接入交换机");
                writer.println();
                writer.println("# 服务器");
                writer.println("192.168.2.100:应用服务器");
                writer.println("192.168.2.101:数据库服务器");
                writer.println();
                writer.println("# 安全设备");
                writer.println("10.0.0.1:防火墙");
                writer.println("10.0.0.2:入侵检测");
            } catch (Exception e) {
                log.error("创建示例文件失败: {}", file.getAbsolutePath(), e);
            }
        }

        log.info("已创建示例硬盘录像机文件在目录: {}", dir.getAbsolutePath());
    }

    /**
     * 重新加载所有硬盘录像机配置
     */
    public Map<String, List<DvrHostEntry>> reloadAllDvrHosts() {
        return readAllDvrHosts();
    }

    /**
     * 获取所有硬盘录像机的IP列表
     */
    public List<String> getAllDvrIps() {
        Map<String, List<DvrHostEntry>> allHosts = readAllDvrHosts();
        return new ArrayList<>(allHosts.keySet());
    }
}